from django.shortcuts import render
from django.shortcuts import render_to_response
from django.shortcuts import HttpResponse
from django.views.decorators.csrf import csrf_protect
from django.views.generic import View
from django.contrib.auth.models import User,Group
from django.contrib.auth import authenticate, login, logout
from django.shortcuts import redirect
from django.contrib.auth.decorators import login_required
from rest_framework import viewsets
import json
from .models import Projects
from .models import Tasks

from .serializers import ProjectsSerializers

# Create your views here.
@login_required
def home(request):
    return render(request, 'home.html',{})




class ProjectsView(View):

    def get(self, request, *args, **kwargs):
        p_list = Projects.objects.filter(status='open')
        p_dict = {'data': []}
        for p in p_list:
            item = {
                'create_user':p.create_user.username,
                'title':p.title,
                'description':p.description,
                'start_time':str(p.start_time),
                'end_time':str(p.end_time),
                'status':p.status,
                'user_group_count':p.user_group.user_set.count()
            }
            p_dict['data'].append(item)
        print p_dict
        return HttpResponse(json.dumps(p_dict),'application/json')

    def post(self, request, *args, **kwargs):
        '''
        create project use ajax method
        '''
        is_ajax = request.is_ajax()
        print is_ajax
        if is_ajax is False:
            HttpResponse('only ajax method')
        p = Projects.objects.create(
            title = 'test',
            decription = 'test desc',
            start_time = '2016-01-01',
            end_time = '2017-01-01',
            status = 'open',
        )
        user = User.objects.get(id='1')
        # add user in group
        p.user_group.user_set.add(user)

        return HttpResponse('Post request')

class LoginView(View):

    def get(self, request, *args, **kwargs):
        return render(request, 'login.html',{})

    def post(self, request, *args, **kwargs):
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username,password=password)
        if user is not None:
            login(request,user)
        else:
            pass
        return redirect('/')

class LogoutView(View):

    def get(self, request, *args, **kwargs):
        if not request.user.is_authenticated:
            return redirect('/')
        else:
            logout(request)

            return HttpResponse(json.dumps({'data':'true'}), 'application/json')


class ProjectViewSet(viewsets.ModelViewSet):
    queryset = Projects.objects.all()
    serializer_class = ProjectsSerializers
